package cm.tl.pms.sys.controller;

import cm.tl.pms.common.entity.ErrorEnum;
import cm.tl.pms.common.entity.ResultMsg;
import cm.tl.pms.common.exception.CustomErrorException;
import cm.tl.pms.sys.entity.SysDept;
import cm.tl.pms.sys.entity.SysRole;
import cm.tl.pms.sys.entity.SysUser;
import cm.tl.pms.sys.entity.SysUserRole;
import cm.tl.pms.sys.listener.ExpressExcelUserListen;
import cm.tl.pms.sys.pojo.*;
import cm.tl.pms.sys.service.ISysDeptService;
import cm.tl.pms.sys.service.ISysRoleService;
import cm.tl.pms.sys.service.ISysUserRoleService;
import cm.tl.pms.sys.service.ISysUserService;
import cm.tl.pms.sys.util.PasswordStrengthValidator;
import cm.tl.pms.util.cache.CodeCache;
import cm.tl.pms.util.fileParser.excel.ExcelExportUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 系统-用户管理
 *
 * @author laker
 * @since 2021-08-05
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysUserRoleService sysUserRoleService;
    @Autowired
    ISysDeptService sysDeptService;
    @Resource
    private HttpServletResponse response;


    @GetMapping
    @ApiOperation(value = "分页查询")
    public ResultMsg<Page<SysUser>> pageAll(@RequestParam(required = false, defaultValue = "1") long page,
                                            @RequestParam(required = false, defaultValue = "10") long limit,
                                            Long deptId,
                                            String userId,
                                            String roleId,
                                            Integer enable,
                                            String keyWord) {
        Page<SysUser> roadPage = new Page<>(page, limit);
        List<Long> userIds = new ArrayList<>();
        if (StrUtil.isNotBlank(roleId)) {
            userIds = sysUserRoleService.list(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getRoleId, roleId)).stream()
                    .map(SysUserRole::getUserId).collect(Collectors.toList());
            if (CollUtil.isEmpty(userIds)) {
                return ResultMsg.successfulResult(roadPage);
            }
        }

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(deptId != null, SysUser::getDeptId, deptId)
                .and(StrUtil.isNotBlank(keyWord), i ->
                        i.like(StrUtil.isNotBlank(keyWord), SysUser::getUserName, keyWord)
                                .or()
                                .like(StrUtil.isNotBlank(keyWord), SysUser::getNickName, keyWord)
                )
                .in(CollectionUtils.isNotEmpty(userIds), SysUser::getUserId, userIds)
                .eq(enable != null, SysUser::getEnable, enable)
                .like(StrUtil.isNotBlank(userId), SysUser::getUserId, userId);

        Page<SysUser> pageList = sysUserService.page(roadPage, queryWrapper);
        if (CollectionUtils.isNotEmpty(pageList.getRecords())) {
            pageList.getRecords().forEach(sysUser -> {
                SysDept dept = sysDeptService.getById(sysUser.getDeptId());
                sysUser.setDeptName(Objects.isNull(dept) ? "" : dept.getDeptName());
                sysUser.setDept(dept);

                SysUserRole userRole = sysUserRoleService.getOne(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, sysUser.getUserId()).last("limit 1"));
                if (Objects.nonNull(userRole)) {
                    SysRole role = sysRoleService.getById(userRole.getRoleId());
                    if (Objects.nonNull(role)) {
                        sysUser.setRoleIds(String.valueOf(role.getRoleId()));
                        sysUser.setRoleName(role.getRoleName());
                    }
                }


            });
        }
        return ResultMsg.successfulResult(pageList);
    }

//    @GetMapping("/pageComplexAll")
//    @ApiOperation(value = "复杂分页查询示例")
//    public ResultMsg<Page<SysUser>> pageComplexAll(PageVO page, UserDto userDto) {
//        Page<SysUser> roadPage = page.toPage();
//        Page<SysUser> pageList = sysUserService.page(roadPage, userDto.queryWrapper());
//        return ResultMsg.successfulResult(pageList);
//    }


    /**
     * 获取所有用户
     *
     * @return
     */
    @GetMapping("/getAll")
    public ResultMsg getAll() {
        List<SysUser> list = sysUserService.list();
        if (CollUtil.isNotEmpty(list)) {
            List<FlowAssigneVo> collect = new ArrayList<>();
            collect.add(FlowAssigneVo.builder().name("系统").value("-1").build());
            collect.addAll(list.stream().map(sysUser -> FlowAssigneVo.builder()
                    .name(sysUser.getNickName()).value(String.valueOf(sysUser.getUserId())).build()).collect(Collectors.toList()));
            return ResultMsg.successfulResult(collect);
        }
        return ResultMsg.successfulResult();
    }

    /**
     * 新增或者更新
     *
     * @param param
     * @return
     */
    @PostMapping
    @Transactional
//    @SaCheckPermission("user.update")
    public ResultMsg saveOrUpdate(@RequestBody SysUser param) {

//        if (param.getUserId() == null && param.getDeptId() == null) {
//            throw new CustomErrorException("请选择部门");
//        }

        if (param.getUserId() == null) {
            // 只有超级管理员才能创建用户
            if (StpUtil.getLoginIdAsLong() != 0L) {
                throw new CustomErrorException("只有超级管理员才能创建用户!");
            }
            String password = param.getPassword();
            param.setPassword(SecureUtil.sha256(password));
            param.setCreateTime(LocalDateTime.now());
            sysUserService.save(param);
        } else {
            sysUserService.saveOrUpdate(param);
        }
        if (StrUtil.isNotBlank(param.getRoleIds())) {
            ArrayList<String> list = CollUtil.newArrayList(param.getRoleIds().split(","));
//            list.add(param.getDataRoleId());
            this.saveUserRole(param.getUserId(), list);
        }
        return ResultMsg.successfulResult();
    }


    @PutMapping("/switch")
    @ApiOperation(value = "用户启用停用开关")
//    @SaCheckPermission("user.switch")
    public ResultMsg userSwitch(@RequestBody SysUser param) {
        return ResultMsg.successfulResult(sysUserService.updateById(param));
    }

    private boolean saveUserRole(Long userId, List<String> roleIds) {
        sysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        roleIds.forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(Long.valueOf(roleId));
            sysUserRole.setUserId(userId);
            sysUserRoles.add(sysUserRole);
        });
        return sysUserRoleService.saveBatch(sysUserRoles);
    }


    @PutMapping("/updatePwd")
    @ApiOperation(value = "更新用户密码")
//    @SaCheckPermission("user.update.pwd")
    public ResultMsg updatePwd(@RequestBody PwdQo param) {

        if (!StrUtil.equals(param.getNewPassword(), param.getConfirmPassword())) {
            throw new CustomErrorException("两次输入密码不一致");
        }
        long userId = StpUtil.getLoginIdAsLong();
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUserId, userId)
                .eq(SysUser::getPassword, SecureUtil.sha256(param.getOldPassword())));
        if (sysUser == null) {
            throw new CustomErrorException("旧密码错误");
        }
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(SecureUtil.sha256(param.getNewPassword()));
        sysUserService.updateById(user);
        return ResultMsg.successfulResult();
    }


    /**
     * 上传用户文件
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadUserInfo")
    @ResponseBody
    @Transactional
    public ResultMsg<String> updatePwd(MultipartFile file) {
        log.info("开始上传用户文件" + file.getOriginalFilename());
        StringBuilder sb = new StringBuilder();
        List<SysUser> userList = new ArrayList<>();
        // 处理excel
        try {
            InputStream inputStream = null;
            inputStream = file.getInputStream();

            // 在这里我们要创建一个监听器
            ExpressExcelUserListen excelParamsListen = new ExpressExcelUserListen();
            EasyExcel.read(inputStream, ImportUserDto.class, excelParamsListen)
                    // 读第一张工作表，是从0开始
                    .sheet(0)
                    // 列头占一行
                    .headRowNumber(1)
                    .doRead();
            List<ImportUserDto> dataList = excelParamsListen.getDataList();
            log.info("excel——————解析结果：{}", dataList);
            if (CollectionUtils.isEmpty(dataList)) {
                excelParamsListen.getErrorList().forEach(
                        error -> sb.append(error).append(";")
                );
                return ResultMsg.failResult("文件解析失败:" + sb);
            }
//            List<SysDept> deptList = sysDeptService.list();

//            Map<String, Long> deptMap = deptList.stream()
//                    .collect(Collectors.toMap(
//                            SysDept::getDeptName,  // key 是 DeptName
//                            SysDept::getDeptId,
//                            (existingValue, newValue) -> existingValue// value 是 DeptId
//                    ));


            List<SysRole> roleList = sysRoleService.list();

            Map<String, Long> roleMap = roleList.stream()
                    .collect(Collectors.toMap(
                            SysRole::getRoleName,
                            SysRole::getRoleId
                    ));

            List<SysUser> users = sysUserService.list();
            Map<String, Long> userNameMap = users.stream()
                    .collect(Collectors.toMap(
                            SysUser::getUserName,  // key 是 UserName
                            SysUser::getUserId,
                            (existingValue, newValue) -> existingValue// value 是 UserId
                    ));
//            Set<String> phoneSet = users.stream()
//                    .map(SysUser::getPhone)  // 提取每个用户的手机号
//                    .collect(Collectors.toSet());  // 收集到一个 Set 中
//            Set<String> emailSet = users.stream()
//                    .map(SysUser::getEmail)  // 提取每个用户的手机号
//                    .collect(Collectors.toSet());  // 收集到一个 Set 中

            dataList.forEach(item -> {
                SysUser user = new SysUser();
                BeanUtil.copyProperties(item, user);
                user.setEnable(1);
                user.setLoginFirst(1);
                //20241207新需求设置默认密码123456
                user.setPassword(SecureUtil.sha256("123456"));
                if (StringUtils.isBlank(user.getUserName())) {
                    sb.append("用户名不可为空" + "\r\n");
                    return;
                }
                String userName = user.getUserName();

//                if (StringUtils.isBlank(user.getPhone()) && StringUtils.isBlank(user.getEmail())) {
//                    sb.append(userName + "的手机号/邮箱(二选一必填)" + "\r\n");
//                    return;
//                }
//                if (StringUtils.isNotBlank(user.getPhone())) {
//                    if (phoneSet.contains(user.getPhone())) {
//                        sb.append(userName + "的手机号重复" + "\r\n");
//                        return;
//                    }
//                    phoneSet.add(user.getPhone());
//                }
//                if (StringUtils.isNotBlank(user.getEmail())) {
//                    if (emailSet.contains(user.getEmail())) {
//                        sb.append(userName + "的邮箱重复" + "\r\n");
//                        return;
//                    }
//                    emailSet.add(user.getEmail());
//                }
                if (userNameMap.containsKey(user.getUserName())) {
                    log.info("用户名重复：" + userName);
                    sb.append(userName + "的用户名重复，请检查上传文档用户名是否重复！是否上传了系统已存在的用户！" + "\r\n");
                    return;
                }
                //    对导入用户信息 部门 做处理
//                if (StringUtils.isNotBlank(item.getDeptName())) {
//                    if (deptMap.containsKey(item.getDeptName())) {
//                        user.setDeptId(deptMap.get(item.getDeptName()));
//                    } else {
//                        log.warn("部门不存在 已经添加为 其他 部门" + item.getDeptName());
//                        user.setDeptId(deptMap.get("其他"));
//                    }
//                } else {
//                    sb.append(userName + "的部门名称为空。\r\n");
//                    return;
//                }
                if (StringUtils.isNotBlank(item.getRoleName())) {
                    if (roleMap.containsKey(item.getRoleName())) {
                        user.setRoleId(roleMap.get(item.getRoleName()));
                    } else {
                        sb.append(userName).append("的角色编号不存在，无法添加到系统中。" + "\r\n");
                        return;
                    }
                } else {
                    sb.append(userName + "的角色名称为空。\r\n");
                    return;
                }
                userList.add(user);
                userNameMap.put(user.getUserName(), user.getUserId());
            });
            log.info("excel——————处理后导入前数据：{}", userList);
            if (sb.length() > 0) {
                return ResultMsg.failResult(sb.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件解析失败。" + e.getMessage());
            sb.append("文件解析失败。");
            return ResultMsg.failResult(sb.toString());
        }
        if (userList.size() > 0) {
            sb.append("最终导入成功条数：" + userList.size());
            sysUserService.saveBatch(userList);
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            for (SysUser sysUser : userList) {
                sysUserRoleList.add(new SysUserRole(null, sysUser.getUserId(), sysUser.getRoleId()));
            }
            sysUserRoleService.saveBatch(sysUserRoleList);

            return ResultMsg.data(sb.toString());
        } else {
            return ResultMsg.failResult("无数据导入！");
        }
    }


    /**
     * 导出用户列表
     */
    @GetMapping("exportUserList")
    public void exportExpress() {
        List<SysUser> list = sysUserService.list(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getEnable, 1));
        if (CollUtil.isEmpty(list)) {
            throw new CustomErrorException("暂无数据");
        }
        List<SysDept> deptList = sysDeptService.list();

        Map<Long, String> deptMap = deptList.stream()
                .collect(Collectors.toMap(
                        SysDept::getDeptId,  // key 是DeptId
                        SysDept::getDeptName,
                        (existingValue, newValue) -> existingValue// value 是  DeptName
                ));
        List<ImportUserDto> expressDtoList = new ArrayList<>();
        list.forEach(item -> {
            ImportUserDto expressDto = new ImportUserDto();
            BeanUtil.copyProperties(item, expressDto);
//            expressDto.setDeptName(deptMap.getOrDefault(item.getDeptId(), ""));
            SysUserRole sysUserRole = sysUserRoleService.getOne(Wrappers.lambdaQuery(SysUserRole.class)
                    .eq(SysUserRole::getUserId, item.getUserId())
                    .last("limit 1")
            );
//            expressDto.setRoleIds(Objects.isNull(sysUserRole)?"":sysUserRole.getRoleId().toString());
            expressDtoList.add(expressDto);
        });

        try {
            String fileName = "用户信息导出";
            ExcelExportUtil.exportExcel(response, fileName, ImportUserDto.class, "用户信息", expressDtoList);
//            EasyExcel.write(response.getOutputStream(), ImportUserDto.class).excelType(ExcelTypeEnum.XLSX).sheet("用户信息").doWrite(expressDtoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 重置用户密码
     *
     * @param userId
     * @return
     */
    @PutMapping("/resetPwd/{userId}")
//    @SaCheckPermission("user.reset.pwd")
//    @SaCheckRole("admin")
    public ResultMsg resetPwd(@PathVariable Long userId) {
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(SecureUtil.sha256("123456"));
        user.setLoginFirst(1);
        sysUserService.updateById(user);
        return ResultMsg.successfulResult("已经重置为123456");
    }

    /**
     * 更新用户头像
     *
     * @param userDto
     * @return
     */
    @PutMapping("/updateAvatar")
//    @SaCheckPermission("user.updateAvatar")
    public ResultMsg resetPwd(@RequestBody UserDto userDto) {
        long userId = StpUtil.getLoginIdAsLong();
        SysUser user = new SysUser();
        user.setAvatar(userDto.getAvatar());
        user.setUserId(userId);
        sysUserService.updateById(user);
        return ResultMsg.successfulResult();
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultMsg get(@PathVariable Long id) {
        return ResultMsg.successfulResult(sysUserService.getById(id));
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
//    @SaCheckPermission("user.delete")
    public ResultMsg<Object> delete(@PathVariable Long id) {
        return ResultMsg.successfulResult(sysUserService.removeById(id));
//        return ResultMsg.result(sysUserService.update(Wrappers.lambdaUpdate(SysUser.class).set(SysUser::getEnable, 0).eq(SysUser::getUserId, id)));
    }

    @GetMapping("/getRoles")
    public ResultMsg edit(Long userId, Integer roleType) {
        List<SysRole> allRole = sysRoleService.list(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleType, roleType));
        if (userId != null) {
            List<SysUserRole> myRole = sysUserRoleService.list(Wrappers.<SysUserRole>lambdaQuery()
                    .eq(SysUserRole::getUserId, userId));
            allRole.forEach(sysRole -> {
                myRole.forEach(sysUserRole -> {
                    if (sysRole.getRoleId().equals(sysUserRole.getRoleId())) {
                        sysRole.setChecked(true);
                    }
                });
            });
        } else {
            allRole.stream()
                    .filter(sysRole -> sysRole.getRoleType() == 1)
                    .findFirst()
                    .ifPresent(sysRole -> sysRole.setChecked(true));
            allRole.stream()
                    .filter(sysRole -> sysRole.getRoleType() == 2)
                    .findFirst()
                    .ifPresent(sysRole -> sysRole.setChecked(true));
        }
        return ResultMsg.successfulResult(allRole);
    }


    /**
     * 根据批量删除ids删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batch/{ids}")
//    @SaCheckPermission("dict.delete")
    public ResultMsg<Object> batchRemove(@PathVariable Long[] ids) {
        return ResultMsg.successfulResult(sysUserService.removeByIds(CollUtil.toList(ids)));
//        return ResultMsg.result(sysUserService.update(Wrappers.lambdaUpdate(SysUser.class).set(SysUser::getEnable, 0).in(SysUser::getUserId, CollUtil.toList(ids))));
    }

    /**
     * 手机号注册
     *
     * @param signInDto
     * @return
     */
    @PostMapping("/signInPhone")
    public ResultMsg<String> signIn(@RequestBody @Validated SignInDto signInDto) {
        log.info("username = {}", signInDto.getUsername());
        // 验证用户名是否存在！
        if (sysUserService.verifyUserName(signInDto.getUsername())) {
            return ResultMsg.failResult(ErrorEnum.ERROR_ENUM10023);
        }
        PasswordRetrievalDto dto = signInDto.getRetrievalDto();
        if (!CodeCache.containsCodeAndPhoneOrEmail(dto.getCodeId(), dto.getPhone(), dto.getCode())) {
            return ResultMsg.failResult(ErrorEnum.ERROR_ENUM10024);
        }
        SysUser sysUser = sysUserService.signIn(signInDto.getUsername(), signInDto.getDeptId(), dto.getPhone());
        if (sysUser != null && sysUser.getUserId() != null) {
            sysUserRoleService.addDefaultRole(sysUser.getUserId());
            return ResultMsg.successfulResult();
        } else {
            return ResultMsg.failResult();
        }
    }


    /**
     * 邮箱注册
     *
     * @param signInDto
     * @return
     */
    @PostMapping("/signInEmail")
    public ResultMsg<String> signInEmail(@RequestBody @Validated SignInEmailDto signInDto) {
        log.info("username = {}", signInDto.getUsername());
        // 验证用户名是否存在！
        if (sysUserService.verifyUserName(signInDto.getUsername())) {
            return ResultMsg.failResult(ErrorEnum.ERROR_ENUM10023);
        }
        PasswordRetrievalEmailDto dto = signInDto.getRetrievalDto();
        if (!CodeCache.containsCodeAndPhoneOrEmail(dto.getCodeId(), dto.getEmail(), dto.getCode())) {
            return ResultMsg.failResult(ErrorEnum.ERROR_ENUM10024);
        }
        SysUser sysUser = sysUserService.signInEmail(signInDto.getUsername(), signInDto.getDeptId(), dto.getEmail());

        if (sysUser != null && sysUser.getUserId() != null) {
            sysUserRoleService.addDefaultRole(sysUser.getUserId());
            return ResultMsg.successfulResult();
        } else {
            return ResultMsg.failResult();
        }
    }

    /**
     * 首次登录修改密码
     *
     * @param passwordChangeDto
     * @return
     */
    @PostMapping("/passwordChange")
    public ResultMsg<String> passwordChange(@RequestBody @Validated PasswordChangeDto passwordChangeDto) {
        UserInfoAndPowers userInfo = (UserInfoAndPowers) StpUtil.getSession().get(EasyAdminConstants.CURRENT_USER);
        log.info("userName = {}", userInfo.getUserName());
        // 验证密码强度
        if (!PasswordStrengthValidator.isValidPassword(passwordChangeDto.getNewPass())) {
            return ResultMsg.failResult(ErrorEnum.ERROR_ENUM10021);
        }
        // 验证两次密码是否一致
        if (!StrUtil.equals(passwordChangeDto.getNewPass(), passwordChangeDto.getConfirmPass())) {
            return ResultMsg.failResult(ErrorEnum.ERROR_ENUM10022);
        }
        // 更新密码
        return ResultMsg.result(sysUserService.passwordReset(userInfo.getUserName(), passwordChangeDto.getNewPass()));

    }

    /**
     * 修改用户信息
     *
     * @param modeifyDto
     * @return
     */
    @PostMapping("/modifyingUserInfo")
    public ResultMsg<String> modifyingUserInfo(@RequestBody SysUserModeifyDto modeifyDto) {
        UserInfoAndPowers userInfo = (UserInfoAndPowers) StpUtil.getSession().get(EasyAdminConstants.CURRENT_USER);
        if (StrUtil.isNotBlank(modeifyDto.getPhone()) && !Validator.isMobile(modeifyDto.getPhone())) {
            return ResultMsg.failResult(ErrorEnum.MOBILE_ERROR);
        }
        if (StrUtil.isNotBlank(modeifyDto.getEmail()) && !Validator.isEmail(modeifyDto.getEmail())) {
            return ResultMsg.failResult(ErrorEnum.EMAIL_ERROR);
        }
        return ResultMsg.result(sysUserService.update(Wrappers.lambdaUpdate(SysUser.class)
                .set(StrUtil.isNotBlank(modeifyDto.getNickName()), SysUser::getNickName, modeifyDto.getNickName())
                .set(ObjectUtil.isNotEmpty(modeifyDto.getDeptId()), SysUser::getDeptId, modeifyDto.getDeptId())
                .set(StrUtil.isNotBlank(modeifyDto.getPhone()), SysUser::getPhone, modeifyDto.getPhone())
                .set(StrUtil.isNotBlank(modeifyDto.getEmail()), SysUser::getEmail, modeifyDto.getEmail())
                .set(StrUtil.isNotBlank(modeifyDto.getAvatar()), SysUser::getAvatar, modeifyDto.getAvatar())

                .eq(SysUser::getUserId, userInfo.getUserId())
        ));
    }

}
